import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { userForm, userInfo, userItem } from '@/types/userform'
import type { info } from '@/types/news'
// 定义 Store
export const useMemberStore = defineStore(
  'member',
  () => {
    // 会员信息
    const profile = ref<userInfo>()
    //点赞收藏副本
    let infoArr = ref<info[]>([])
    //搜索历史
    let history = ref<{ title: string, newsId?: number }[]>([])
    // 保存会员信息，登录时使用
    const setProfile = (val: userInfo) => {
      profile.value = val
    }
    const setUserinfo = (val: userItem) => {
      profile.value!.user = val
    }
    // 清理会员信息，退出时使用
    const clearProfile = () => {
      profile.value = undefined
      infoArr.value = []
    }
    const set_infoArr = (data: info[]) => {
      infoArr.value = data
    }
    const click_like = (newsId: number) => {
      infoArr.value.forEach(e => {
        if (e.newsId == newsId) {
          e.clickLike = !e.clickLike
          if (e.clickLike)
            e.likeCount++
          else
            e.likeCount--
        }
      })
    }
    const click_favourte = (newsId: number) => {
      infoArr.value.forEach((e) => {
        if (e.newsId == newsId) {
          e.clickFavorite = !e.clickFavorite
          if (e.clickFavorite)
            e.favoriteCount++
          else
            e.favoriteCount--
        }
      })
    }
    //设置浏览历史
    const set_history = (val: { title: string, newsId?: number }) => {
      let index = history.value.findIndex(item=>item.title==val.title);
      
      if (index !== -1) {
        // 如果元素存在于数组中
        history.value.splice(index, 1);
        history.value.unshift(val)
      } else {
        history.value.unshift(val)
      }
    }
    //清空历史
    const clear_history = () => {
      history.value = []
    }
    // 记得 return
    return {
      profile,
      infoArr,
      history,
      setProfile,
      clearProfile,
      setUserinfo,
      set_infoArr,
      click_like,
      click_favourte,
      set_history,
      clear_history
    }
  },
  // TODO: 持久化
  {
    //网页端配置
    //persist: true,
    //小程序端配置
    persist: {
      storage: {
        getItem(key) {
          return uni.getStorageSync(key)
        },
        setItem(key, value) {
          return uni.setStorageSync(key, value)
        }
      }
    }
  },
)
